package top.eggcode.setup.config.ds;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import top.eggcode.plugins.mds.Source;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 数据源配置
 */
@Configuration
public class DsConfig {


    @Primary
    @Bean(name = "DsMaster")
    @ConfigurationProperties("spring.datasource.master")
    public DataSource createDsMaster() {
        //return new HikariDataSource();
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "DsSlave")
    @ConfigurationProperties("spring.datasource.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.slave", name = "enabled", havingValue = "true")
    public DataSource createDsSlave() {

        //return new HikariDataSource();
        return DataSourceBuilder.create().build();
    }

    /**
     * 默认数据源配置和多数据源配置
     *
     * @return 数据源
     */
    @Bean(name = "routingDataSource")
    public SimpleRoutingDataSource dynamicDataSource(@Qualifier("DsMaster") DataSource master, @Qualifier("DsSlave") DataSource slave) {
        SimpleRoutingDataSource routingDs = new SimpleRoutingDataSource();
        // 默认数据源
        routingDs.setDefaultTargetDataSource(master);
        // 配置多数据源
        Map<Object, Object> sourceMap = new HashMap<>(16);
        sourceMap.put(Source.MASTER.getKey(), master);
        sourceMap.put(Source.SLAVE.getKey(), slave);
        // 默认
        routingDs.setDefaultTargetDataSource(master);
        // 全部数据源
        routingDs.setTargetDataSources(sourceMap);
        return routingDs;
    }



/*    @Primary
    @Bean(name = "DsMasterSet")
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSourceProperties  ds1DataSource() {
        return new DataSourceProperties();
    }

    @Primary
    @Bean(name = "DsMaster")
    public DataSource configDsMaster(@Qualifier("DsMasterSet") DataSourceProperties set) {
        return set.initializeDataSourceBuilder().build();
    }

    @Bean(name = "DsSlaveSet")
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSourceProperties DsSlaveSet() {
        return new DataSourceProperties();
    }

    @Bean("DsSlave")
    public DataSource ds2DataSource(@Qualifier("DsSlaveSet") DataSourceProperties set) {
        return set.initializeDataSourceBuilder().build();
    }*/
}
